<template>
  <div class="data-export-content">
    <!-- <div class="hint">
      说明：50例以下的导出将直接导出到用户端本地，50例以上的导出将导出到服务器，用户可进行其他操作，稍后刷新界面，在导出结果中选择导出文件，点击下载即可将数据下载到本地！
    </div>
    <div class="export-result-content">
      <el-row :gutter="20">
        <el-col :span="24" style="display: flex">
          <span style="line-height: 32px; font-size: 16px">导出结果</span>
          <el-col :span="10">
            <el-select v-model="value" placeholder="请选择导出结果/导出历史进行下载">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>
        </el-col>
      </el-row>
    </div> -->
    <div class="export-btn-list" v-for="item in exportBtnList" :key="item.parentId">
      <span style="font-size: 16px; color: #0057ff; font-weight: 550; margin-bottom: 10px">{{
        item.title
      }}</span>
      <span style="font-size: 14px; color: red; margin-bottom: 10px" v-if="item.parentId === '3'"
        >操作顺序：选择分组->选择病例->选择阶段->选择CRF->导出</span
      >
      <span
        style="font-size: 14px; color: black; margin-bottom: 5px"
        v-html="item.hint"
        @click="handleClick"
      ></span>
      <div style="display: flex">
        <el-button
          type="primary"
          v-for="v in item.btnArr"
          :key="v.type"
          @click="handleExport(v, item)"
          >{{ v.btnName }}</el-button
        >
      </div>
    </div>

    <div class="scale-main">
      <div class="group-content">
        <span class="c-title">1.分组选择</span>
        <div class="group-list">
          <div
            class="group-list-line"
            v-for="(item, index) in groupList"
            :key="item.id"
            @click="handleGroupName(item)"
            :style="{
              backgroundColor: groupLineValue.id === item.id ? '#428bca' : '',
              color: groupLineValue.id === item.id ? '#fff' : '',
              borderBottom: index === 0 ? 'none' : '1px solid #dddddd',
            }"
          >
            <Memo style="width: 16px; height: 16px; margin-right: 2px; margin-left: 20px" />
            <span>{{ item.name }}</span>
          </div>
        </div>
      </div>
      <div class="enter-group-content" style="width: 40%">
        <span class="c-title">2.病例选择</span>
        <avue-crud
          :data="caseData"
          :option="caseOption"
          :table-loading="tableLoading"
          v-model:page="page"
          ref="crud"
          @selection-change="selectionChange"
          @current-change="currentChange"
          @size-change="sizeChange"
        >
        </avue-crud>
      </div>
      <div class="crf-content">
        <div class="crf-title-content">
          <span class="c-title" style="margin-right: 10px">3.阶段选择</span>
          <!-- <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="city in cities" :key="city" :label="city.label" :value="city.value">
              {{ city.label }}
            </el-checkbox>
          </el-checkbox-group> -->
        </div>
        <el-tree
          ref="treeRef"
          style="max-width: 600px"
          :data="crfTreedata"
          show-checkbox
          node-key="id"
          highlight-current
          :props="defaultProps"
          @check="handleNodeCheck"
        />
      </div>
    </div>
    <el-dialog
      v-model="isPdfExport"
      title="PDF导出"
      top="50px"
      width="1200"
      body-class="QR-code-dialog-body"
      @close="closeIndicatorSet"
    >
      <pdfExport ref="pdfExportRef" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isPdfExport = false">关 闭</el-button>
          <el-button type="primary" @click="handlePdf"> 导出PDF </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>

import pdfExport from './dataExportMenu/pdfExport.vue';
import { groupListOfTrial, clinicalCase, customExportPdf } from '@/api/trial/trial';
import { getList } from '@/api/clinicalcase/clinicalCase';
import { treeWithCrf } from '@/api/group/group';
import { exportBlob } from '@/api/common';
import { getToken } from '@/utils/auth';
import website from '@/config/website';
import { downloadXls } from '@/utils/util';
import { dateNow } from '@/utils/date';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { ref, reactive, computed, onMounted, defineEmits, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import caseloadOptions from '@/option/caseload/caseload';
import { useStore } from 'vuex';
import { useRoute, useRouter } from 'vue-router';
const route = useRoute();
const emit = defineEmits();
const routerQuery = ref({});
routerQuery.value = route.query;
const router = useRouter();
const store = useStore();
let options = ref([]);
let value = ref('');
let groupLineValue = ref({});
let groupList = ref([]);
let crud = ref(null);
let selectionList = ref([]);
let enterGroupList = ref([]);
let caseOption = ref({
  index: false,
  height: '400',
  // calcHeight: 330,
  // maxHeight: 300,
  selection: true,
  addBtn: false,
  editBtn: false,
  viewBtn: false,
  delBtn: false,
  menu: false,
  align: 'center',
  searchShowBtn: false,
  refreshBtn: false,
  gridBtn: false,
  columnBtn: false,
  reserveSelection: true,
  column: [
    {
      label: '病例姓名',
      prop: 'name',
      type: 'input',
      overHidden: true,
    },
    {
      label: '状态',
      prop: 'status',
      type: 'select',
      dicUrl: '/api/blade-system/dict-biz/dictionary?code=clinical_case_status',
      props: {
        label: 'dictValue',
        value: 'dictKey',
      },
      overHidden: true,
      // width: 100,
    },
  ],
});
let tableLoading = ref(false);
let caseData = ref([]);
const page = ref({
  pageSize: 10,
  currentPage: 1,
  total: 4,
});

const treeRef = ref(null);

const checkedCities = ref([]);
let selectedCrfNodes = ref([]);
let isPdfExport = ref(false);
let pdfExportRef = ref(null);
const cities = [
  {
    label: '不合并全选',
    value: '1',
  },
  { label: '合并全选', value: '2' },
];

const defaultProps = {
  children: 'children', // 子节点字段
  label: 'title',
};
console.log(defaultProps);
/*
{
    id: 1,
    label: 'Level one 1',
    children: [
      {
        id: 4,
        label: 'Level two 1-1',
        children: [
          {
            id: 9,
            label: 'Level three 1-1-1',
          },
          {
            id: 10,
            label: 'Level three 1-1-2',
          },
        ],
      },
    ],
  },
*/
const crfTreedata = ref([]);

// 阶段选择，多选框change事件
const handleCheckedCitiesChange = val => {
  if (val.length > 1) {
    checkedCities.value.shift();
  }
  if (checkedCities.value.length === 1) {
    exportBtnList.value[2].btnArr = [
      {
        type: 2,
        btnName: 'PDF导出',
      },
      {
        type: 4,
        btnName: '全阶段导出',
      },
    ];
  } else {
    exportBtnList.value[2].btnArr = [
      {
        btnName: 'Excel导出',
        type: 1,
      },
      {
        btnName: 'PDF导出',
        type: 2,
      },
      {
        btnName: '历史导出',
        type: 3,
      },
    ];
  }
};

const handleClick = event => {
  if (event.target.classList.contains('clickable')) {
    handleGoGroupAdmin();
  }
};
// 高级检索点击事件
const handleGoGroupAdmin = () => {
  emit('dataExportChange', 5);
};
// 分组选择---每一项点击事件
const handleGroupName = item => {
  groupLineValue.value = item;
  initTreeWithCrf(item.id);
  selectionClear();
  onLoad(page.value);
};
onMounted(() => {
  if (routerQuery.value.trialId) {
    initData();
  }
});
const initData = () => {
  // 各分组
  groupListOfTrial(routerQuery.value.trialId).then(res => {
    groupList.value = res.data.data;
    groupLineValue.value = groupList.value[0];
    // CRF阶段接口方法---默认显示第一个分组的CRF阶段
    initTreeWithCrf(groupList.value[0].id);
    onLoad(page.value);
  });
};
const initTreeWithCrf = groupId => {
  treeWithCrf(groupId).then(res => {
    crfTreedata.value = formatTreeData(res.data.data);
    console.log('这里这里这里', crfTreedata.value);
  });
};
// 处理接口数据转换
const formatTreeData = rawData => {
  return rawData.map(node => {
    // 处理原始 children（如果有）
    const originalChildren = node.children ? formatTreeData(node.children) : [];

    // 处理 CRF 列表
    const crfChildren =
      node.crfList?.map(crf => ({
        ...crf,
        title: crf.crfName,
        type: 'crf',
        id: crf.id.toString(),
      })) || [];

    return {
      ...node,
      type: 'phase',
      children: [...originalChildren, ...crfChildren],
    };
  });
};

// CRF阶段，复选框选中事件
const handleNodeCheck = (checkedNode, checkedStatus) => {
  // 过滤掉所有父节点（type为'phase'的节点）
  const onlyCrfNodes = checkedStatus.checkedNodes.filter(
    node => node.type === 'crf' && (!node.children || node.children.length === 0)
  );

  // 更新全局变量
  selectedCrfNodes.value = onlyCrfNodes;
};
// 获取选中数据的工具函数（可在提交时使用）
const getSelectedCrfData = () => {
  if (!treeRef.value) return [];

  // 获取所有选中节点
  const allCheckedNodes = treeRef.value.getCheckedNodes();

  // 过滤并返回CRF节点
  return allCheckedNodes.filter(
    node => node.type === 'crf' && (!node.children || node.children.length === 0)
  );
};
const handleExport = (row, parentRow) => {
  if (parentRow.parentId === '1') {
    let urlObj = {
      病例导出: '/blade-clinicalcase/clinicalCase/export-clinicalCase',
      纳排导出: '/blade-collectinfo/collectInfo/npExport',
      入组导出: '/blade-collectinfo/collectInfo/groupInfoExport',
      其他定制数据导出: '/blade-collectinfo/collectInfo/otherExport',
      文件列表导出: '/blade-information/information/listWithTrialExport',
    };
    let downloadUrl = `${urlObj[row.btnName]}?${website.tokenHeader}=${getToken()}`;
    let values = {};
    if (row.type == 1 || row.type == 5) {
      values.trial = routerQuery.value.trialId;
    } else {
      values.trialId = routerQuery.value.trialId;
    }
    ElMessageBox.confirm('是否导出数据?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      NProgress.start();
      exportBlob(downloadUrl, values).then(res => {
        downloadXls(res.data, `${row.btnName}${dateNow()}.xlsx`);
        NProgress.done();
      });
    });
  }
  if (parentRow.parentId === '2') {
    router.push({
      path: '/trial/variable',
      query: {
        btnType: row.type,
        trialId: routerQuery.value.trialId,
        selectTab: '6',
      },
    });
  }
  if (parentRow.parentId === '3') {
    if (!ids.value) {
      ElMessage.warning('请至少选择一个病例');
      return;
    }
    if (!phaseCrfIds.value) {
      ElMessage.warning('请至少选择一张CRF');
      return;
    }
    if (row.type === 1) {
      let downloadUrl = `/blade-collectinfo/collectInfo/customExportExcel?${
        website.tokenHeader
      }=${getToken()}`;
      let values = {
        trialId: routerQuery.value.trialId,
        groupId: groupLineValue.value.id,
        clinicalCaseIds: ids.value,
        phaseCrfIds: phaseCrfIds.value,
      };
      ElMessageBox.confirm('是否导出数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        NProgress.start();
        exportBlob(downloadUrl, values).then(res => {
          downloadXls(res.data, `${row.btnName}${dateNow()}.xlsx`);
          NProgress.done();
        });
      });
    }
    if (row.type === 2) {
      customExportPdf(
        routerQuery.value.trialId,
        groupLineValue.value.id,
        ids.value,
        phaseCrfIds.value
      ).then(res => {
        console.log(res);
        const DATA = res.data.data;
        if (DATA.length > 0) {
          isPdfExport.value = true;
          nextTick(() => {
            pdfExportRef.value.open(DATA);
          });
        }
      });
    }
  }
};

const handlePdf = () => {
  nextTick(async() => {
    pdfExportRef.value.pdf(groupLineValue.value.name);
    // const element = pdfExportRef.value;

    // // 使用 html2canvas 将 DOM 元素渲染成 Canvas
    // const canvas = await html2canvas(element, {
    //   scale: 2, // 提高清晰度
    //   useCORS: true,
    // });

    // const imgData = canvas.toDataURL('image/png');
    // const pdf = new jsPDF('p', 'mm', 'a4'); // 定义 PDF 尺寸和方向
    // const imgWidth = 210; // A4 纸宽度 (mm)
    // const imgHeight = (canvas.height * imgWidth) / canvas.width;

    // pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight);
  });
};

// ids 计算属性
const ids = computed(() => {
  return selectionList.value.map(ele => ele.id).join(',');
});
// ids 计算属性
const phaseCrfIds = computed(() => {
  return selectedCrfNodes.value.map(ele => ele.id).join(',');
});
const selectionChange = list => {
  selectionList.value = list;
};
const selectionClear = () => {
  selectionList.value = [];
  crud.value.toggleSelection();
};
const currentChange = currentPage => {
  page.value.currentPage = currentPage;
  // TabRefreshChange();
  onLoad(page.value);
};
const sizeChange = pageSize => {
  page.value.pageSize = pageSize;
  // TabRefreshChange();
  onLoad(page.value);
};
const onLoad = (page, params = {}) => {
  tableLoading.value = true;

  let values = {
    descs: 'create_time',
    groupId: groupLineValue.value.id,
    trial: routerQuery.value.trialId,
    ...params,
  };

  getList(page.currentPage, page.pageSize, values).then(res => {
    const DATA = res.data.data;
    page.total = DATA.total;
    caseData.value = DATA.records;
    tableLoading.value = false;
    // selectionClear();
  });
};

let exportBtnList = ref([
  {
    title: '全部导出',
    //hint: '导出该业务中该角色最高权限下可看到的所有病例的数据。如想挑选部分病例进行导出，可前往入组管理<span style="color: #6b57ff;font-weight550;cursor: pointer;"  class="clickable">高级检索</span>中进行操作。',
    hint: '导出该业务中该角色最高权限下可看到的所有病例的数据。',
    parentId: '1',
    btnArr: [
      {
        btnName: '病例导出',
        type: 1,
      },
      {
        btnName: '纳排导出',
        type: 2,
      },
      {
        btnName: '入组导出',
        type: 3,
      },
      {
        btnName: '其他定制数据导出',
        type: 4,
      },
      {
        btnName: '文件列表导出',
        type: 5,
      },
      // {
      //   btnName: 'CDISC导出',
      //   type: 6,
      // },
    ],
  },
  {
    title: '变量挑选',
    hint: '自定义设置变量，导出所选变量下的数据',
    parentId: '2',
    btnArr: [
      {
        btnName: '横向挑选',
        type: 1,
      },
      {
        btnName: '纵向挑选',
        type: 2,
      },
      {
        btnName: '历史挑选',
        type: 3,
      },
    ],
  },
  {
    title: '自定义导出',
    hint: '依次选择分组、病例、阶段和CRF表，实现不同CRF表导出到不同Sheet表中',
    parentId: '3',
    btnArr: [
      {
        btnName: 'Excel导出',
        type: 1,
      },
      {
        btnName: 'PDF导出',
        type: 2,
      },
      // {
      //   btnName: '历史导出',
      //   type: 3,
      // },
    ],
  },
]);
</script>
<style scoped lang="scss">
.data-export-content {
  width: 90%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.hint {
  margin: 0 0 20px 0;
  font-size: 16px;
  color: red;
}
.export-result-content {
  height: 50px;
  border-bottom: 1px solid #d5d5d5;
}
.export-btn-list {
  height: auto;
  border-bottom: 1px solid #d5d5d5;
  display: flex;
  flex-direction: column;
  margin-top: 20px;
  padding-bottom: 10px;
}
.scale-main {
  width: 100%;
  height: auto;
  display: flex;
  justify-content: space-between;
}
.group-content,
.enter-group-content {
  width: 29%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.enter-group-content {
  ::v-deep .avue-crud__header {
    display: none;
  }
}
.c-title {
  font-size: 14px;
  color: black;
  font-weight: 550;
  margin-bottom: 5px;
}
.group-list {
  width: 100%;
  height: 420px;
  color: #428bca;
  overflow-y: auto;
  overflow-x: hidden;
}
.group-list-line {
  width: 99%;
  height: 40px;
  display: flex;
  align-items: center;
  border: 1px solid #dddddd;
  cursor: pointer;
}
.enter-group-list {
  width: 100%;
  height: 420px;
  color: #00bb00;
  overflow-y: auto;
  overflow-x: hidden;
}
.enter-group-list-line {
  width: 99%;
  height: 40px;
  display: flex;
  align-items: center;
  border: 1px solid #dddddd;
  cursor: pointer;
}
.crf-content {
  width: 29%;
  height: auto;
  ::v-deep .avue-crud__header {
    display: none;
  }
}
.crf-title-content {
  display: flex;
  align-items: center;
}
</style>
